<?php

namespace chick1993\util\libs\exceptions;

use Throwable;

class RuntimeException extends \RuntimeException
{
    /**
     * @var array
     */
    protected $data;

    public function __construct($message = "", ?int $code = null, array $data = [], Throwable $previous = null)
    {
        if ($message instanceof Throwable) {
            $e = $message;
            $message = $e->getMessage();
            if (is_null($code)) {
                $code = $e->getCode();
            }

            if (method_exists($e, 'getData')) {
                $data = $data ?: $e->getData();
            }

            $previous = $previous ?: $e;
        }

        if (is_array($message) || is_object($message)) {
            $message = json_encode($message, 256);
        }

        $this->data = $data;

        if (is_null($code)) $code = 0;

        parent::__construct($message, $code, $previous);

    }

    /**
     * 获取其他异常数据
     * @return array
     */
    public function getData(): array
    {
        return $this->data;
    }

    /**
     * 获取其他异常数据，getData别名
     * @return array
     */
    public function getError(): array
    {
        return $this->data;
    }

}